package com.base;

import com.google.common.primitives.Ints;

import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

/**
 * @author: sun.hongliang
 * @create: 2019/08/07 17:14
 */
public class Queue {

    public static void main(String[] args) throws InterruptedException {
        DelayQueue<DelayMessage> delayQueue = new DelayQueue<>();
        DelayMessage take = delayQueue.take();
    }
}

class DelayMessage implements Delayed {
    private int id;
    private String body; // 消息内容
    private long excuteTime;// 延迟时长，这个是必须的属性因为要按照这个判断延时时长。

    public DelayMessage(int id, String body, long delayTime) {
        this.id = id;
        this.body = body;
        this.excuteTime = TimeUnit.NANOSECONDS.convert(delayTime, TimeUnit.MILLISECONDS) + System.nanoTime();
    }


    public int getId() {
        return id;
    }

    public String getBody() {
        return body;
    }

    public long getExcuteTime() {
        return excuteTime;
    }

    @Override
    public long getDelay(TimeUnit unit) {
        return unit.convert(this.excuteTime - System.nanoTime(), TimeUnit.NANOSECONDS);
    }

    @Override
    public int compareTo(Delayed delayed) {
        DelayMessage o = (DelayMessage) delayed;
        return Ints.compare(id, o.getId());
    }
}
